import { createWebHistory, createRouter } from "vue-router";
import { useUserStore } from "@/store";
import { showToast } from "@/utils/vant-ui.js";
const routes = [
  {
    path: "/",
    component: () => import("@/views/layout/LayoutContainer.vue"),
    redirect: "/topic",
    children: [
      {
        path: "/topic",
        component: () => import("@/views/layout/topic/index.vue"),
      },
      {
        path: "/topic-content",
        component: () => import("@/views/layout/topicContent/index.vue"),
      },
      {
        path: "/judge",
        component: () => import("@/views/layout/judgePage/index.vue"),
      },
      {
        path: "/person",
        component: () => import("@/views/layout/showPMessage/index.vue"),
      },
    ],
  },
  { path: "/search", component: () => import("@/views/search/index.vue") },
  { path: "/search/list", component: () => import("@/views/search/list.vue") },
  { path: "/login", component: () => import("@/views/login/index.vue") },
  { path: "/register", component: () => import("@/views/register/index.vue") },
  { path: "/add-topic", component: () => import("@/views/addTopic/index.vue") },
  { path: "/setting", component: () => import("@/views/setting/index.vue") },
  { path: "/user/follow", component: () => import("@/views/follow/index.vue") },
  {
    path: "/user/topic",
    component: () => import("@/views/userTopic/index.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});
//登录访问拦截
// 返回值： 1.放行：undefined or true
// 2.false不放行默认放行
// 3.返回路由地址字符串 跳转到指定路由
router.beforeEach((to) => {
  console.log("已经经过了导航前置守卫");
  //如果不是登录页
  //如果没有token 跳转到登录页
  if (to.path !== "/login" && to.path !== "/register") {
    const userStore = useUserStore();
    const token = userStore.token;
    if (!token) {
      showToast({
        message: "请先登录",
        duration: 1000,
      });
      return "/login";
    }
  }
});
export default router;
